<template>
  <div class="app-container version-page">
    <el-form v-show="showSearch" :inline="true" :model="queryParams" ref="queryRef" label-width="80px">
      <el-form-item label="版本号" prop="versionNumber">
        <el-input
          v-model="queryParams.versionNumber"
          placeholder="请输入版本号"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平台" prop="applicablePlatforms">
        <el-input
          v-model="queryParams.applicablePlatforms"
          placeholder="Android、iOS 等"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布日期" prop="releaseDate" class="range-item">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 380px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:version:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:version:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:version:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:version:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本号" align="center" prop="versionNumber" min-width="120" />
      <el-table-column label="发布日期" align="center" prop="releaseDate" min-width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.releaseDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安卓包" align="center" min-width="140">
        <template #default="scope">
          <el-link v-if="scope.row.androidUrl" :href="buildDownloadUrl(scope.row.androidUrl)" type="primary" target="_blank">
            下载安装包
          </el-link>
          <span v-else class="text-muted">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="主要更新" align="center" prop="mainFeatureUpdates" :show-overflow-tooltip="true" min-width="160" />
      <el-table-column label="修复问题" align="center" prop="fixedIssues" :show-overflow-tooltip="true" min-width="160" />
      <el-table-column label="适用平台" align="center" prop="applicablePlatforms" min-width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.applicablePlatforms" size="small">{{ scope.row.applicablePlatforms }}</el-tag>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" min-width="140" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:version:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:version:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="760px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本号" prop="versionNumber">
              <el-input v-model="form.versionNumber" placeholder="例如 v1.2.0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布日期" prop="releaseDate">
              <el-date-picker
                v-model="form.releaseDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择发布时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用平台" prop="applicablePlatforms">
              <el-input v-model="form.applicablePlatforms" placeholder="如 Android / 全平台" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安卓安装包" prop="androidUrl">
              <file-upload
                v-model="form.androidUrl"
                :limit="1"
                :fileSize="200"
                :fileType="['apk']"
                :isShowTip="false"
              />
              <div class="upload-hint">仅支持 apk，最大 200MB</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主要更新" prop="mainFeatureUpdates">
              <el-input
                v-model="form.mainFeatureUpdates"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="概述本次更新的亮点"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="修复问题" prop="fixedIssues">
              <el-input
                v-model="form.fixedIssues"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="列出修复的主要问题"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                maxlength="200"
                show-word-limit
                placeholder="可填写灰度范围、升级提示等信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Version">
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import FileUpload from "@/components/FileUpload";
import { addVersion, delVersion, exportVersion, getVersion, listVersion, updateVersion } from "@/api/system/version";

const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const versionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    versionNumber: undefined,
    applicablePlatforms: undefined
  },
  rules: {
    versionNumber: [{ required: true, message: "版本号不能为空", trigger: "blur" }],
    releaseDate: [{ required: true, message: "发布日期不能为空", trigger: "change" }],
    androidUrl: [{ required: true, message: "请上传安卓安装包", trigger: "change" }],
    mainFeatureUpdates: [{ required: true, message: "请填写主要更新内容", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

function buildDownloadUrl(url) {
  if (!url) {
    return "";
  }
  return url.startsWith("http") ? url : baseUrl + url;
}

/** 查询版本列表 */
function getList() {
  loading.value = true;
  listVersion(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    versionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    versionNumber: undefined,
    androidUrl: undefined,
    releaseDate: undefined,
    mainFeatureUpdates: undefined,
    fixedIssues: undefined,
    applicablePlatforms: undefined,
    remark: undefined
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  title.value = "新增版本";
  form.value.releaseDate = proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
  open.value = true;
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getVersion(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改版本";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      const action = form.value.id ? updateVersion(form.value) : addVersion(form.value);
      action.then(() => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const versionIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除版本编号为\"' + versionIds + '\"的数据项？').then(function() {
    return delVersion(versionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出操作 */
function handleExport() {
  exportVersion(proxy.addDateRange(queryParams.value, dateRange.value));
}

getList();
</script>

<style scoped lang="scss">
.version-page {
  .range-item {
    margin-right: 12px;
  }
  .text-muted {
    color: #909399;
  }
  .upload-hint {
    margin-top: 4px;
    font-size: 12px;
    color: #909399;
  }
}
</style>
